package com.closer.codebox.api;

import com.closer.codebox.biz.cpp.CppCodeSandbox;
import com.closer.codebox.biz.java.JavaCodeSandbox;
import com.closer.codebox.biz.python.PythonCodeSandbox;
import com.closer.codebox.support.dto.ExecuteCodeRequest;
import com.closer.codebox.support.dto.JudgeInfo;
import com.closer.codebox.support.enums.SupportLanguageEnum;
import com.closer.codebox.support.exception.ErrorCode;
import com.closer.codebox.support.exception.ThrowUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController("/")
@Slf4j
public class MainController {

    /**
     * 定义鉴权请求头
     */
    private static final String AUTH_REQUEST_HEADER = "codesandbox-auth";

    /**
     * 定义鉴权请求头中的密钥
     */
    private static final String AUTH_REQUEST_SECRET = "$W$~vrZwe7z&L!ht^U%fF2zZzHTjWSwY%@ZeEJ^*(qZ()D3npx";

    private final JavaCodeSandbox javaCodeSandbox;

    private final PythonCodeSandbox pythonCodeSandbox;

    private final CppCodeSandbox cppCodeSandbox;

    public MainController(JavaCodeSandbox javaCodeSandbox, PythonCodeSandbox pythonCodeSandbox, CppCodeSandbox cppCodeSandbox) {
        this.javaCodeSandbox = javaCodeSandbox;
        this.pythonCodeSandbox = pythonCodeSandbox;
        this.cppCodeSandbox = cppCodeSandbox;
    }

    @PostMapping("/executeCode")
    JudgeInfo executeCode(@RequestBody ExecuteCodeRequest params, HttpServletRequest request) {
        var authHeader = request.getHeader(AUTH_REQUEST_HEADER);
        ThrowUtils.throwIf(!authHeader.equals(AUTH_REQUEST_SECRET), ErrorCode.NO_AUTH_ERROR, "未授权");
        ThrowUtils.throwIf(params == null, ErrorCode.PARAMS_ERROR, "参数为空");
        var language = params.getLanguage();

        //todo 使用策略模式优化
        if (SupportLanguageEnum.JAVA.getValue().equals(language))
        {
            log.info("开始执行Java代码");
            return javaCodeSandbox.executeCode(params);
        }
        else if (SupportLanguageEnum.PYTHON.getValue().equals(language))
        {
           log.info("开始执行Python3代码");
           return pythonCodeSandbox.executeCode(params);
        }
        else if (SupportLanguageEnum.CPP.getValue().equals(language))
        {
            log.info("开始执行CPP代码");
            return cppCodeSandbox.executeCode(params);
        }
        else {
            return JudgeInfo.builder()
                    .message("不支持的语言类型")
                    .time(null)
                    .memory(null)
                    .build();
        }
    }

}
